package com.he.services.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.he.config.DingTalkAppConfig;
import com.he.mapper.DeptMapper;
import com.he.pojo.Dept;
import com.he.pojo.DingDept;
import com.he.pojo.ServiceResult;
import com.he.services.DeptService;
import com.taobao.api.ApiException;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.he.config.UrlConstant.*;

/**
 * @program: usersync
 * @description:
 * @author: xin.he
 * @create: 2021-06-06 13:10
 **/
@Service
public class DeptServiceImpl implements DeptService {
    private static final Logger log = LoggerFactory.getLogger(DeptServiceImpl.class);

    @Autowired
    DeptMapper deptMapper;

    @Autowired
    DingTalkAppConfig dingTalkAppConfig;

    @Autowired
    DingTokenServiceImpl dingTokenService;

    @Override
    public List<Dept> queryAll() {
        return deptMapper.queryAll();
    }

    @Override
    public int add(Dept dept) {
        return deptMapper.add(dept);
    }

    @Override
    public Dept queryByDeptName(String deptName) {
        return deptMapper.queryByDeptName(deptName);
    }

    @Override
    public Dept queryByDeptId(String dId) {
        return deptMapper.queryByDeptId(dId);
    }


    @Override
    public ServiceResult<String> dingDeptSync() {
        // 获取accessToken
        ServiceResult<String> accessTokenSr = dingTokenService.getAccessToken();
        if (!accessTokenSr.isSuccess()) {
            return ServiceResult.failure(accessTokenSr.getCode(), accessTokenSr.getMessage());
        }
        String accessToken = accessTokenSr.getResult();

        DingTalkClient client = new DefaultDingTalkClient(URL_V2_DEPARTMENT_LIST);
        OapiV2DepartmentListsubRequest request = new OapiV2DepartmentListsubRequest();
        request.setHttpMethod("GET");

        OapiV2DepartmentListsubResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("获取钉钉部门列表失败 {}", URL_DEPARTMENT_LIST, e);
            e.printStackTrace();
        }
        if (!response.isSuccess()){
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
       /* List<Dept> list = new ArrayList<>();
        if (response.getResult().size() != 0){
           for (OapiV2DepartmentListsubResponse.DeptBaseResponse deptBase : response.getResult()){
               Dept dept = new Dept();
               dept.setDeptName(deptBase.getName());
               dept.setDid(deptBase.getDeptId());
               dept.setLongNumber("1");
               dept.setParent(deptBase.getParentId());
               list.add(dept);
               deptMapper.add(dept);
           }
        }*/
        Set<Long> deptSubIds = new HashSet<>();
        Set<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseSet = new HashSet<>();
        if (response.getResult().size() != 0 || response.getResult().size() !=0 ) {
            for (OapiV2DepartmentListsubResponse.DeptBaseResponse deptBase : response.getResult()) {
                deptBaseSet.add(deptBase);
            }
        }
        return null;
    }

    @Override
    public String saveDingDeptList() throws Exception {
        log.info("获取钉钉通讯录组织架构");
        // 获取accessToken
        ServiceResult<String> accessTokenSr = dingTokenService.getAccessToken();
        if (!accessTokenSr.isSuccess()){
            throw new Exception("获取accessToken失败:" + accessTokenSr.getMessage());
        }
        String accessToken = accessTokenSr.getResult();
        DingTalkClient client = new DefaultDingTalkClient(URL_DEPARTMENT_LIST);
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setHttpMethod("GET");

        OapiDepartmentListResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("获取钉钉部门列表失败{}", URL_DEPARTMENT_LIST, e);
        }
        int deptCount = response.getDepartment().size();
        if (deptCount != 0){
            for (OapiDepartmentListResponse.Department department :response.getDepartment()){
                Long deptId = department.getId();
                Long parent = department.getParentid();
                Dept dept = new Dept();
                dept.setDid(deptId);
                dept.setLongNumber(getLongNumberV1(deptId.toString()));
                dept.setDeptName(department.getName());
                dept.setParent(parent == null? 1L : parent);
                deptMapper.add(dept);
            }
            return "同步了" +deptCount+ "个部门";
        }
        return "同步了0个部门";
    }

    @Override
    public List<String> getDeptIdLIst() {
        return deptMapper.getDeptIdList();
    }

    /**
     * 根据id获取父部门id列表
     *
     * @param id
     * @return
     */
    public String getLongNumberV2(Long id ) throws Exception {

        log.info("获取钉钉通讯录组织架构");
        // 获取accessToken
        ServiceResult<String> accessTokenSr = dingTokenService.getAccessToken();
        if (!accessTokenSr.isSuccess()){
            throw new Exception("获取accessToken失败:" + accessTokenSr.getMessage());
        }
        String accessToken = accessTokenSr.getResult();

        DingTalkClient client = new DefaultDingTalkClient(URL_V2_DEPID_PARENT_LIST);
        OapiV2DepartmentListparentbydeptRequest request = new OapiV2DepartmentListparentbydeptRequest();
        request.setHttpMethod("GET");
        request.setDeptId(id);

        OapiV2DepartmentListparentbydeptResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("获取钉钉部门列表失败{}", URL_V2_DEPID_PARENT_LIST, e);
            throw new Exception(e.getErrMsg());
        }
        List<Long> parentIdsList = response.getResult().getParentIdList();
        if (parentIdsList.size() == 1) {
            return parentIdsList.get(0).toString();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = parentIdsList.size() - 1; i > 0; i--) {
            sb.append(parentIdsList.get(i) + "!");
        }

        return sb.substring(0, sb.toString().length() - 1);
    }


    /**
     * 根据id获取父部门id列表
     * 将Parent列表用!拼接成字符串
     * @param id
     * @return
     */
    public String getLongNumberV1(String id) throws Exception {

        log.info("获取钉钉通讯录子部门");
        // 获取accessToken
        ServiceResult<String> accessTokenSr = dingTokenService.getAccessToken();
        if (!accessTokenSr.isSuccess()){
            throw new Exception("获取accessToken失败:" + accessTokenSr.getMessage());
        }
        String accessToken = accessTokenSr.getResult();

        DingTalkClient client = new DefaultDingTalkClient(URL_DEPID_PARENT_LIST);
        OapiDepartmentListParentDeptsByDeptRequest request = new OapiDepartmentListParentDeptsByDeptRequest();
        request.setHttpMethod("GET");
        request.setId(id);

        OapiDepartmentListParentDeptsByDeptResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("获取钉钉部门列表失败{}", URL_DEPID_PARENT_LIST, e);
            throw new Exception(e.getErrMsg());
        }
        List<Long> parentIdsList = response.getParentIds();
        if (parentIdsList.size() == 1) {
            return parentIdsList.get(0).toString();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = parentIdsList.size() - 1; i > 0; i--) {
            sb.append(parentIdsList.get(i) + "!");
        }
        return sb.substring(0, sb.toString().length() - 1);
    }



}
